# -*- coding: UTF-8 -*-
from flask import Flask,redirect, url_for,flash
from flask import render_template
from flask import request
import time
from pyecharts import Bar
from pyecharts import Scatter3D
from pyecharts_javascripthon.api import TRANSLATOR

from werkzeug.security import generate_password_hash, check_password_hash
#from flask_login import LoginManager, login_user, login_required, logout_user, current_user, UserMixin
import flask_login


class User_tmp(flask_login.UserMixin):


    @property
    def is_active(self):
        print("is_active")
        return True

    @property
    def is_authenticated(self):
        print("is_authenticated")
        return True

    @property
    def is_anonymous(self):
        print("is_anonymous")
        return False

    def get_id(self):
        print("get_id")
        try:
            return (str(int(time.time())))
        except AttributeError:
            raise NotImplementedError('No `id` attribute - override `get_id`')
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

REMOTE_HOST = "https://pyecharts.github.io/assets/js"
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dev'

login_manager = flask_login.LoginManager()
login_manager.init_app(app)



#login key
@login_manager.user_loader
def load_user(user_id):
    print("load_user")
    print(user_id)
    user = User_tmp()
    print(user)
    return user

login_manager.session_protection ="strong"
login_manager.login_view = 'login'
login_manager.login_message ='Please login first!'
login_manager.login_message_category = "info"
login_manager.refresh_view = 'login'#"/" #用户需要重新进行身份验证时要重定向到的视图的名称
login_manager.needs_refresh_message = 'Refresh for login!'#用户重定向到“需要刷新”页面时闪出的消息。


@app.route('/')
def hello_world():
    #print("hello world")
    #print(request.path)
    #print(request.full_path)
    #print request.args.__str__()
    #return 'Hello World'
    return render_template('Home.html')

@app.route('/index')
def index():
    flash('index')
    user = { 'nickname': 'sunsiyuan' } # fake user
    return render_template("index.html",
        title = 'Home',
        user = user)
#变量规则
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):

    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id
@app.route('/projects/')
def projects():
    return 'The project page'
@app.route('/about')
def about():
    return 'The about page'
#构造 URL
@app.route('/admin')
def hello_admin():
   return 'Hello Admin'


@app.route('/guest/<guest>')

def hello_guest(guest):
   return 'Hello %s as Guest' % guest


@app.route('/user/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest', guest = name))
#如果匹配，则使用url_for()将应用程序重定向到hello_admin()函数，否则重定向到将接收的参数作为guest参数传递给它的hello_guest()函数。
#url_for('static', filename='style.css')
#这个文件应该存储在文件系统上的 static/style.css
#@app.route('/login', methods=['POST', 'GET'])#http://127.0.0.1:5000/login
#def login():
#    error = None
#    if request.method == 'POST':
#        #print(request.headers)
#        print(request.stream.read())
#        #print(request)
#        #print(request.form)
#        #print(request.args)
#        return '这是post请求'
#    else:
#        print(request.args)
#        return request.args.get('info')
#        request.args.getlist('p')  # 返回一个list
#        print(request.form)
#        print(request.form['name'])
#        print(request.form.get('name'))
#        print(request.form.getlist('name'))
#        print(request.form.get('nickname', default='little apple'))
        #处理JSON格式的请求数据
        #print(type(request.json))
        #print(request.json)
        #响应JSON - 方案 from flask import Flask, request, jsonify
        #return Response(json.dumps(result),  mimetype='application/json')
        #result = {'sum': request.json['a'] + request.json['b']}
        #return jsonify(result)
#        return '这是get请求'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    #return render_template('login.html', error=error)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if not username or not password:
            #flash('Invalid input.')
            return redirect(url_for('login'))
        user = User_tmp()

        #if username == user.username and user.validate_password(password):
        flask_login.login_user(user)
        #flash('Login success.')
        flash('Logged in successfully.')

        next = request.args.get('next')
        print("next")
        print(next)
        # is_safe_url should check if the url is safe for redirects.
        # See http://flask.pocoo.org/snippets/62/ for an example.
        #if not next_is_valid(next):
        #    return abort(400)
        return redirect(next )
        #return redirect(url_for('secret'))

        #flash('Invalid username or password.')
        #return redirect(url_for('login'))

    return render_template('login.html')

@app.route('/logout')
@flask_login.login_required # 用于视图保护，后面会详细介绍
def logout():
    flask_login.logout_user() # 登出用户

    return redirect(url_for('index')) # 重定向回首页

@app.route('/secret')
@flask_login.login_required
def secret():
   return 'niubil'
##############################################

@app.route('/view')
def view():
    #bar = Bar("我的第一个图表", "这里是副标题")
    #bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90])
    # bar.print_echarts_options() # 该行只为了打印配置项，方便调试时使用
    #return bar.render()  # 生成本地 HTML 文件
    ##print(bar.render_embed())
    #return (bar.render_embed())
    _bar = bar_chart()
    javascript_snippet = TRANSLATOR.translate(_bar.options)
    return render_template(
        "view.html",
        chart_id=_bar.chart_id,
        host=REMOTE_HOST,
        renderer=_bar.renderer,
        my_width="100%",
        my_height=600,
        custom_function=javascript_snippet.function_snippet,
        options=javascript_snippet.option_snippet,
        script_list=_bar.get_js_dependencies(),
    )


def bar_chart():
    bar = Bar("我的第一个图表", "这里是副标题")
    bar.add(
        "服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90]
    )
    return bar

#一个新的思路
#@app.context_processor
#def inject_user():
#    return "sun"

#@app.errorhandler(400)
#def bad_request(e):
#    return render_template('errors/400.html'), 400


#@app.errorhandler(404)
#def page_not_found(e):
#    return render_template('errors/404.html'), 404


#@app.errorhandler(500)
#def internal_server_error(e):
#    return render_template('errors/500.html'), 500

#用户认证 Flask-Login
#>>> from werkzeug.security import generate_password_hash, check_
#password_hash
#>>> pw_hash = generate_password_hash('dog') # 为密码 dog 生成密码
#散列值
#>>> pw_hash # 查看密码散列值
#'pbkdf2:sha256:50000$mm9UPTRI$ee68ebc71434a4405a28d34ae3f170757f
#b424663dc0ca15198cb881edc0978f'
#>>> check_password_hash(pw_hash, 'dog') # 检查散列值是否对应密码 dog
#True
#>>> check_password_hash(pw_hash, 'cat') # 检查散列值是否对应密码 cat
#False

#Flask-Login


if __name__ == '__main__':
   app.run()